package com.mconnect.msurvey.controller;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

import com.mconnect.msurvey.model.Questions;
import com.mconnect.msurvey.util.HibernateUtil;

public class QuestionsManager extends HibernateUtil{
	
	protected List<String> getNonEmptyFields(Questions questions){
		List<String> questionsList = new ArrayList<String>();
		if(!questions.getQuestion1().equals("all")){
			questionsList.add("question1='" + questions.getQuestion1() + "'");
		} if(!questions.getQuestion2().equals("all")){
			questionsList.add("question2='" + questions.getQuestion2() + "'");
		}if(!questions.getQuestion3().equals("all")){
			questionsList.add("question3='" + questions.getQuestion3() + "'");
		}if(!questions.getQuestion4().equals("all")){
			questionsList.add("question4='" + questions.getQuestion4() + "'");
		}if(!questions.getQuestion5().equals("all")){
			questionsList.add("question5='" + questions.getQuestion5() + "'");
		}if(!questions.getQuestion6().equals("all")){
			questionsList.add("question6='" + questions.getQuestion6() + "'");
		}
		return questionsList;
	
	
	}

	protected String getSQLQuery(List<String> nonEmptyQuestions){
		int number = nonEmptyQuestions.size();
		
		String sqlQuery = "";
		if(!nonEmptyQuestions.isEmpty()){
			String sql = "select id_survey from questions where ";
			if(number == 1){
				sqlQuery = sql + nonEmptyQuestions.get(0);
			}else if(number == 2){
				sqlQuery = sql + nonEmptyQuestions.get(0) + " and " + nonEmptyQuestions.get(1);
			}else if(number == 3){
				sqlQuery = sql + nonEmptyQuestions.get(0) + " and " + nonEmptyQuestions.get(1) + " and " + nonEmptyQuestions.get(2);
			}else if(number == 4){
				sqlQuery = sql + nonEmptyQuestions.get(0) + " and " + nonEmptyQuestions.get(1) + " and " + nonEmptyQuestions.get(2) + " and " + nonEmptyQuestions.get(3);
			}else if(number == 5){
				sqlQuery = sql + nonEmptyQuestions.get(0) + " and " + nonEmptyQuestions.get(1) + " and " + nonEmptyQuestions.get(2) + " and " + nonEmptyQuestions.get(3) + " and " + nonEmptyQuestions.get(4);
			}else if(number == 6){
				sqlQuery = sql + nonEmptyQuestions.get(0) + " and " + nonEmptyQuestions.get(1) + " and " + nonEmptyQuestions.get(2) + " and " + nonEmptyQuestions.get(3) + " and " + nonEmptyQuestions.get(4) + " and " + nonEmptyQuestions.get(5);
			}
		}
		return sqlQuery;
	}
	
	@SuppressWarnings("unchecked")
	public List<Questions> getQuestionsAfterIdFromDB(int id_survey){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
       session.getTransaction().begin();
        
        List<Questions> questionsList = new ArrayList<Questions>();
        questionsList = session.createQuery("from Questions where id_survey=" + id_survey).list();
        
        session.getTransaction().commit();
       
		return questionsList;
	}

}
